from flask import Flask, request
from threading import Thread
import logging

# 关闭 Flask 默认日志输出
logging.getLogger('werkzeug').setLevel(logging.ERROR)

class OneBotServer:
    def __init__(self, host="0.0.0.0", port=8080):
        self.host = host
        self.port = port
        self.app = Flask(__name__)
        self.server_thread = None

    def on_path(self, path: str, callback):
        """
        为指定路径注册回调函数
        :param path: URL 路径，如 "/"、"/private"
        :param callback: 处理函数，接受一个参数：data (dict)
        """
        def handler():
            if not request.is_json:
                return '', 400
            data = request.get_json()
            # 异步执行，避免阻塞 HTTP 响应
            Thread(target=callback, args=(data,), daemon=True).start()
            return '', 200

        # 注册路由
        self.app.add_url_rule(path, view_func=handler, methods=['POST'])
        return self  # 支持链式调用

    def start(self):
        """启动服务（非阻塞）"""
        def run():
            self.app.run(
                host=self.host,
                port=self.port,
                threaded=True,
                debug=False,
                use_reloader=False
            )

        self.server_thread = Thread(target=run, daemon=True)
        self.server_thread.start()
        print(f"[{self._now()}] 服务启动: http://{self.host}:{self.port}/")
        return self

    def _now(self):
        from datetime import datetime
        return datetime.now().strftime('%Y-%m-%d %H:%M:%S')